<script setup lang="ts">
import {Chart} from "@vue-chart/echart"
const props = defineProps({
  dataSource: {
    type: Array,
    default: () => []
  },
  priceRange: {
    type: Array,
    default: () => []
  },
})
const options = ref({
  // 统计表名称
  title: {
    text: '月销量分析（参考值）',
    left: 'center',
    top: 20,
    textStyle: {
      color: '#333',
      fontSize: 14,
      fontWeight: 'bold'
    }
  },
  tooltip: {
    trigger: 'item',
  },
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      data: [],
      type: 'bar',
      showBackground: true,
    }
  ]
})
const calcRangeChartData = ()=>{
  showChart.value = false;
  //  根据传入的价格区间计算数据总销量 totalSale
  const {priceRange,dataSource} = props
  const xAxisData = []
  const seriesData = []
  for(let i = 0;i<priceRange.length;i++){
    if(i>0){
      // console.log(priceRange[i]);
      const name = `${priceRange[i-1]}~${priceRange[i]}元`
      // console.log(name);
      const totalSaleItems = dataSource.filter(item=>Number(item.price)>priceRange[i-1]&&Number(item.price)<=priceRange[i]);
      // 求totalSale和
      const number = totalSaleItems.reduce((total,item)=>total+Number(item.monthSale),0)
      xAxisData.push(name)
      seriesData.push(number)
    }
  }
  options.value.series[0].data = seriesData
  options.value.xAxis.data = xAxisData
  nextTick(()=>{
    showChart.value = true;
  })
}
onMounted(()=>{
  calcRangeChartData()
})
watch(() => props.dataSource, () => {
  calcRangeChartData()
},{deep:true})
watch(() => props.priceRange, () => {
  calcRangeChartData()
},{deep:true})
const showChart = ref(false)
</script>

<template>
  <Chart :options="options" v-if="showChart" style="height: 300px;"/>
</template>

<style scoped>

</style>
